package com.imonsoft.sqm.web.business.ipic_system;

import com.imonsoft.common.constant.ConstantSqm;
import com.imonsoft.common.exception.SystemException;
import com.imonsoft.common.util.DateUtil;
import com.imonsoft.common.util.StringUtil;
import com.imonsoft.sqm.pojo.basedata.Supplier;
import com.imonsoft.sqm.pojo.business.ipic_system.Claim;
import com.imonsoft.sqm.service.basedata.IpicTargetService;
import com.imonsoft.sqm.service.basedata.SupplierService;
import com.imonsoft.sqm.service.business.ipic_system.ClaimService;
import com.imonsoft.sqm.service.business.ipic_system.IPICService;
import com.imonsoft.sqm.vo.business.ipic_system.ClaimVo;
import com.imonsoft.sqm.vo.business.ipic_system.IPICSummaryVo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.DatasetRenderingOrder;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.LevelRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.List;

@Controller
@RequestMapping("/business/ipic_system/supplier_ipic_summary")
public class SupplierIPICSummaryController {
    protected final Log logger = LogFactory.getLog(getClass());
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private IPICService ipicService;
    @Autowired
    private IpicTargetService ipicTargetService;
    @Autowired
    private ClaimService claimService;

    private DecimalFormat decimalFormat =new DecimalFormat(",###");//格式化类


    @RequestMapping("/listUI.do")
    public void listUI(ModelMap model,HttpSession session,IPICSummaryVo ipicSummaryVo) {
        if(StringUtils.isEmpty(ipicSummaryVo.getYear())){
            ipicSummaryVo.setYear(DateUtil.getNowDate().substring(0,4));
        }
        model.put("entity", ipicSummaryVo);

        if(null!=ipicSummaryVo.getSupplierId()){
            Supplier supplier=supplierService.get(ipicSummaryVo.getSupplierId());
            ipicSummaryVo.setSupplierCode(supplier.getCode());
            ipicSummaryVo.setSupplierName(supplier.getName());

            Map<String, Object> searchMap = new HashMap<String, Object>();//查询条件
            searchMap.put("supplierId", ipicSummaryVo.getSupplierId());
            searchMap.put("year", ipicSummaryVo.getYear());
            searchMap.put("type", ConstantSqm.TYPE_CLAIM);
            Map<String,Object> resultMap=new HashMap<String, Object>();//计算结果
            List<IPICSummaryVo> ipicSummaryVoList = new ArrayList<IPICSummaryVo>();
            //获得当前供应商每个月的ipic值，用于Accumulate，Rolling...提高效率
            Map<Integer,Integer> ipicMonthMap=new HashMap<Integer, Integer>();

            for(int monthTemp=1;monthTemp<=12;monthTemp++){
                IPICSummaryVo entity = new IPICSummaryVo();
                entity.setMonth(StringUtil.paddingZero("" + monthTemp, 2));
                searchMap.put("month", StringUtil.paddingZero(""+monthTemp,2));

                //--月份数据--
                ipicService.calIPICMonthData(searchMap, resultMap);
                entity.setIpicM((Integer)resultMap.get("ipicMonth"));
                entity.setIpicMonth(decimalFormat.format(resultMap.get("ipicMonth")));

                ipicMonthMap.put(monthTemp,(Integer)resultMap.get("ipicMonth"));
                //--至当前月份，累计数据的平均值--
                int ipicAccumulate=0;
                for(int temp=1;temp<=monthTemp;temp++){
                    ipicAccumulate=ipicAccumulate+ipicMonthMap.get(temp);
                }
                entity.setIpicAverageY(ipicAccumulate/monthTemp);
                entity.setIpicAverageYear(decimalFormat.format(ipicAccumulate/monthTemp));

                //--滚动数据--
                int ipicRolling=0;
                if(monthTemp==1){
                    ipicRolling=ipicMonthMap.get(1);
                }else if(monthTemp==2){
                    ipicRolling=ipicMonthMap.get(1)+ipicMonthMap.get(2);
                }else{
                    for(int temp=monthTemp-2;temp<=monthTemp;temp++){
                        ipicRolling=ipicRolling+ipicMonthMap.get(temp);
                    }
                }
                entity.setIpicRolling(decimalFormat.format(ipicRolling));

                //ppm
                ipicService.calPPMMonthData(searchMap,resultMap);
                entity.setPpmMonth(decimalFormat.format(resultMap.get("ppmM")));
                ipicService.calPPMAccumulateData(searchMap,resultMap);
                entity.setPpmAccumulateYear(decimalFormat.format(resultMap.get("ppmA")));

                ipicSummaryVoList.add(entity);


            }
            model.put("entityList",ipicSummaryVoList);
            //claims
            List<Claim> claimList=claimService.findClaimBySupplierYear(ipicSummaryVo.getSupplierId(),Integer.valueOf(ipicSummaryVo.getYear()));
            List<ClaimVo> claimVoList=new ArrayList<ClaimVo>();
            for(Claim source:claimList){
                ClaimVo target=new ClaimVo();
                BeanUtils.copyProperties(source,target);
                target.setStartDateStr(DateUtil.date2string(source.getStartDate()));
                claimVoList.add(target);
            }
            model.put("claimVoList",claimVoList);

            //last year ipic average value
            int lastYear=Integer.parseInt(ipicSummaryVo.getYear())-1;
            int lastYearIPICAverage=calLastYearIPICAverage(searchMap, resultMap);
            double ipicTarget=ipicTargetService.getIpicTargetValue(ipicSummaryVo.getSupplierId(),ipicSummaryVo.getYear());
            model.put("lastYear",lastYear);
            searchMap.put("year",StringUtil.paddingZero(lastYear+"",2));
            model.put("lastYearIPICAverage",lastYearIPICAverage);
            //this year ipic target
            model.put("IPICTarget",ipicTarget);


            model.put("imagePath",
                    drawToJSP(session,createChart(
                            createDataSetBar(lastYear,lastYearIPICAverage),
                            createDataSetLine(ipicSummaryVoList,lastYear+1),
                            createDataSetHorizontal(lastYear+1,ipicTarget))));
        }
    }
    private int calLastYearIPICAverage(Map<String, Object> searchMap,Map<String,Object> resultMap){
        int ipicTotal=0;
        for(int monthTemp=1;monthTemp<=12;monthTemp++){
            searchMap.put("month", StringUtil.paddingZero(""+monthTemp,2));
            //--月份数据--
            ipicService.calIPICMonthData(searchMap, resultMap);
            ipicTotal=ipicTotal+(Integer)resultMap.get("ipicMonth");
        }
        return ipicTotal/12;
    }


    /**
     * step1:创建 简单数据集对象
     * @return
     */
    private CategoryDataset createDataSetLine(List<IPICSummaryVo> ipicSummaryVoList,int nowYear) {
        DefaultCategoryDataset dataset=new DefaultCategoryDataset();
        dataset.setValue(0,"Month",(nowYear-1)+"AverageValue");
        for(IPICSummaryVo ipicSummaryVo:ipicSummaryVoList){
            dataset.setValue(ipicSummaryVo.getIpicM(),"Month",nowYear+"-"+ipicSummaryVo.getMonth());
        }
        dataset.setValue(0,"YearAverage",(nowYear-1)+"AverageValue");
        for(IPICSummaryVo ipicSummaryVo:ipicSummaryVoList){
            dataset.setValue(ipicSummaryVo.getIpicAverageY(),"YearAverage",nowYear+"-"+ipicSummaryVo.getMonth());
        }
        return dataset;
    }
    private CategoryDataset createDataSetBar(int lastYear,int lastYearIPICAverage) {
        //创建柱状图数据集
        DefaultCategoryDataset dataset=new DefaultCategoryDataset();
        dataset.setValue(lastYearIPICAverage,lastYear+" AverageIPIC",lastYear+"AverageValue");
        for(int month=1;month<=12;month++){
            dataset.setValue(0,lastYear+" AverageIPIC",(lastYear+1)+"-"+StringUtil.paddingZero(month+"",2));
        }
        return dataset;
    }
    private CategoryDataset createDataSetHorizontal(int nowYear,double ipicTarget) {
        //创建柱状图数据集
        DefaultCategoryDataset dataset=new DefaultCategoryDataset();
//        dataset.setValue(0,nowYear+" TargetIPIC",(nowYear-1)+"AverageValue");
        for(int month=1;month<=12;month++){
            dataset.setValue(ipicTarget,nowYear+" TargetIPIC",nowYear+"-"+StringUtil.paddingZero(month+"",2));
        }
        return dataset;
    }
    /**
     * step2:创建图表
     * @param
     * @return
     */
    private JFreeChart createChart(CategoryDataset barDateSet,CategoryDataset dataset2,CategoryDataset dataset3) {
        JFreeChart chart = ChartFactory.createBarChart(
                "", //图表的标题
                "",  //目录轴的显示标签
                "",   //数值轴的显示标签
                barDateSet, //数据集
                PlotOrientation.VERTICAL,  //图表方式：V垂直;H水平
                true, // 是否显示图例
                false, // 是否显示工具提示
                false // 是否生成URL
        );

        Font font = new Font("黑体", Font.BOLD, 15);
        chart.getLegend().setItemFont(font);
        chart.getTitle().setFont(font);

        CategoryPlot plot = chart.getCategoryPlot();
        plot.setRangeGridlinesVisible(true);// 设置横虚线可见
        plot.setRangeGridlinePaint(Color.gray);// 虚线色彩
        plot.getRangeAxis().setUpperMargin(0.15);
        plot.setBackgroundPaint(new Color(255, 255, 204));
        plot.setDatasetRenderingOrder(DatasetRenderingOrder.REVERSE);//折线在柱面前面显示
        plot.getDomainAxis().setTickLabelFont(font);
        plot.getDomainAxis().setLabelFont(font);
        plot.getRangeAxis().setLabelFont(font);

        plot.setDataset(1, dataset2);//设置第二个数据集
        plot.setDataset(2, dataset3);

        CategoryAxis categoryaxis = plot.getDomainAxis();
        categoryaxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);

        BasicStroke basicStroke=new BasicStroke(2.0f);

        LineAndShapeRenderer lineAndShapeRenderer = new LineAndShapeRenderer();
        lineAndShapeRenderer.setBaseLinesVisible(true);
        lineAndShapeRenderer.setBaseShapesVisible(true);
        lineAndShapeRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        lineAndShapeRenderer.setBaseItemLabelsVisible(true);
        lineAndShapeRenderer.setSeriesPaint(0,Color.GREEN);
        lineAndShapeRenderer.setSeriesStroke(0, basicStroke);
        lineAndShapeRenderer.setSeriesStroke(1, basicStroke);
        plot.setRenderer(1,lineAndShapeRenderer);

        LineAndShapeRenderer lineAndShapeRendererTarget = new LineAndShapeRenderer();
        lineAndShapeRendererTarget.setBaseLinesVisible(true);
        lineAndShapeRendererTarget.setBaseShapesVisible(false);
        lineAndShapeRendererTarget.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        lineAndShapeRendererTarget.setBaseItemLabelsVisible(false);
        lineAndShapeRendererTarget.setSeriesPaint(0,Color.black);
        lineAndShapeRendererTarget.setSeriesStroke(0,basicStroke);
        plot.setRenderer(2,lineAndShapeRendererTarget);


        return chart;
    }
    /**
     * step3: 输出图表到tomcat临时目录
     * @param session
     * @param
     */
    private String drawToJSP(HttpSession session,JFreeChart chart){
        String url ="";
        try {
            String fileName = ServletUtilities.saveChartAsPNG(chart, 800, 600, session);
            //ServletUtilities是面向web开发的工具类，返回一个字符串文件名,文件名自动生成，生成好的图片会自动放在服务器（tomcat）的临时文件下（temp）

            url = "/DisplayChart?filename=" + fileName;
            //根据文件名去临时目录下寻找该图片，这里的/DisplayChart路径要与配置文件里用户自定义的<url-pattern>一致
        }catch (SystemException se) {
            logger.info(se.getMessage());
        }catch (IOException e) {
            logger.error(e.getMessage());
        }catch (Exception e) {
            logger.error(e.getMessage());
        }
        return url;
    }
}
